<!--
 * @Author: your name
 * @Date: 2022-10-28 15:37:10
 * @LastEditTime: 2022-12-08 12:02:17
 * @LastEditors: yuhan
 * @Description: 
 * @FilePath: \ft-apiadmin\apiadmin\src\views\staticFile\index.vue
-->
<template>
  <div class="staticFile">
    <el-card class="box-card bottom-in" v-loading="uploadAppendData.loading">
      <template #header>
        <div class="card-header">
          <span class="excelTag"
            >Excel文件：<el-tag>{{ uploadAppendData.file.name || "暂无上传文件" }}</el-tag></span
          >
          <el-upload
            ref="upload"
            class="upload-File"
            action="/staticData/warehousing"
            :limit="1"
            :on-change="handelChange"
            :on-exceed="handleExceed"
            :auto-upload="false"
            :show-file-list="false"
            :multiple="false"
          >
            <template #trigger>
              <el-button type="primary">选择</el-button>
            </template>
          </el-upload>
          <el-button class="button" type="primary" @click="downloadTemplate">模板下载</el-button>
          <el-button class="button" type="success" @click="exportLatelyFile">导出</el-button>
          <el-button
            class="button"
            type="success"
            :icon="InfoFilled"
            @click="operatInstruceDialog.visible = true"
            >操作提示</el-button
          >
          <RefreshBtn />
        </div>
      </template>
      <div class="card-content">
        <el-tabs
          v-if="staticDataList.data.length > 0"
          type="border-card"
          tab-position="left"
          v-model="staticDataList.activeIndex"
        >
          <el-tab-pane
            v-for="(staticData, staticDataIndex) in staticDataList.data"
            :key="staticData.name"
            :label="staticData.name"
            :name="staticDataIndex"
          >
            <template #label>
              <span class="custom-tabs-label">
                <el-icon><Document /></el-icon>
                <span>{{ staticData.name }}</span>
              </span>
            </template>
            <el-table :data="staticData.data" class="sheetTable right-in" border>
              <el-table-column type="index" width="50" align="center" />
              <el-table-column prop="name" label="name" width="180" align="center" />
              <el-table-column prop="value" label="value" width="180" align="center" />
            </el-table>
          </el-tab-pane>
        </el-tabs>
        <el-empty v-else description="暂无数据" />
      </div>
    </el-card>
    <!-- sheetNames选择框 -->
    <el-dialog
      class="chooseSheetDialog"
      v-model="chooseSheetDialog.visible"
      title="Excel数据选择"
      width="30%"
      center
      :show-close="false"
    >
      <el-checkbox v-model="chooseSheetDialog.checkAll" @change="handleCheckAllSheets"
        >全选</el-checkbox
      >
      <el-checkbox-group v-model="chooseSheetDialog.checkedList">
        <el-checkbox
          v-for="sheetItem in chooseSheetDialog.data"
          :key="sheetItem"
          :label="sheetItem"
          >{{ sheetItem }}</el-checkbox
        >
      </el-checkbox-group>
      <template #footer>
        <span class="dialog-footer">
          <el-popconfirm
            title="全局静态数据将被全部覆盖！"
            :teleported="false"
            @confirm="
              () => {
                chooseSheetDialog.visible = false;
                handleUploadFile();
              }
            "
          >
            <template #reference>
              <el-button type="primary"> 确定 </el-button>
            </template>
          </el-popconfirm>
        </span>
      </template>
    </el-dialog>
    <!-- 操作步骤提示框 -->
    <el-dialog
      class="operatInstruceDialog"
      v-model="operatInstruceDialog.visible"
      title="操作步骤提示"
      width="700px"
      center
    >
      <el-steps direction="vertical" :active="4">
        <el-step title="下载模板">
          <template v-slot:description>
            <el-image :src="previewImg1" fit="fit" :preview-src-list="[previewImg1]" />
          </template>
        </el-step>
        <el-step title="按格式填写数据">
          <template v-slot:description>
            <h3>普通格式</h3>
            <el-image :src="previewImg2" fit="fit" :preview-src-list="[previewImg2]" />
            <h3>若包含单位，格式如下(值和单位之间用"&"分隔)</h3>
            <el-image :src="previewImg3" fit="fit" :preview-src-list="[previewImg3]" />
          </template>
        </el-step>
        <el-step title="选择文件并上传数据">
          <template v-slot:description>
            <h3>选择本地文件（符合数据格式）</h3>
            <el-image :src="previewImg4" fit="fit" :preview-src-list="[previewImg4]" />
            <h3>
              勾选要上传的sheet后"确定"上传。<span style="color: red"
                >tips:上传的数据会覆盖原来的数据</span
              >
            </h3>
            <el-image :src="previewImg5" fit="fit" :preview-src-list="[previewImg5]" />
            <h3>请求地址以及传参展示</h3>
            <el-image
              :src="previewImg5_1"
              fit="fit"
              :preview-src-list="[previewImg5_1, previewImg5_2]"
            />
            <el-image
              :src="previewImg5_2"
              fit="fit"
              :preview-src-list="[previewImg5_1, previewImg5_2]"
            />
          </template>
        </el-step>
        <el-step title="等待上传完毕，查看数据">
          <template v-slot:description>
            <el-image :src="previewImg6" fit="fit" :preview-src-list="[previewImg6]" />
          </template>
        </el-step>
      </el-steps>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="operatInstruceDialog.visible = false"> 关闭 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from "vue";
import { ElMessage } from "element-plus";
import { Document, InfoFilled } from "@element-plus/icons-vue";
import { getFormDataUrl, blobToFile } from "@/utils/index.js";
import request from "@/utils/request";
import * as XLSX from "xlsx";
import apiUrl from "@/config/api.mjs";
import { useStore } from "vuex";
import RefreshBtn from "@/components/RefreshBtn/index.vue";
import previewImg1 from "./img/preview-1.png";
import previewImg2 from "./img/preview-2.png";
import previewImg3 from "./img/preview-3.png";
import previewImg4 from "./img/preview-4.png";
import previewImg5 from "./img/preview-5.png";
import previewImg5_1 from "./img/preview-5-1.png";
import previewImg5_2 from "./img/preview-5-2.png";
import previewImg6 from "./img/preview-6.png";
const store = useStore();
const apis = apiUrl.staticFile;

const upload = ref(null);
// 上传时附带projectId和SheetNames
const uploadAppendData = ref({
  loading: false,
  file: "",
  projectId: "",
  sheets: [],
});
// 选择sheet列表的弹窗
const chooseSheetDialog = ref({
  visible: false,
  data: [],
  checkedList: [],
  checkAll: false, // 是否全选sheet
});
// 全选sheet
const handleCheckAllSheets = (checkAll) => {
  chooseSheetDialog.value.checkAll = checkAll;
  if (checkAll) {
    chooseSheetDialog.value.checkedList = chooseSheetDialog.value.data;
  } else {
    chooseSheetDialog.value.checkedList = [];
  }
};
// 监听已选择的sheet
watch(
  () => chooseSheetDialog.value.checkedList,
  (nv) => {
    uploadAppendData.value.sheets = nv;
    chooseSheetDialog.value.checkAll =
      chooseSheetDialog.value.data.length === chooseSheetDialog.value.checkedList.length;
  }
);

// 选择文件，读取excel文件sheet列表，然后打开sheet选择框
const handelChange = (uploadFile, uploadFiles) => {
  var files = uploadFile.raw;
  uploadAppendData.value.file = files;
  var fileReader = new FileReader();
  fileReader.onload = function (ev) {
    try {
      const data = XLSX.read(ev.target.result, {
        type: "binary",
      });
      chooseSheetDialog.value.data = data.SheetNames || [];
      if (chooseSheetDialog.value.data.length > 0) {
        chooseSheetDialog.value.checkedList = [];
        chooseSheetDialog.value.visible = true;
      } else {
        chooseSheetDialog.value.visible = false;
        ElMessage({
          type: "waring",
          message: "文件无内容",
        });
      }
    } catch (e) {
      chooseSheetDialog.value.visible = false;
      ElMessage({
        type: "waring",
        message: "文件类型不正确",
      });
    }
  };
  fileReader.readAsBinaryString(files);
};

// 重复上传则覆盖
const handleExceed = (files) => {
  upload.value.clearFiles();
  upload.value.handleStart(files[0]);
};

// 上传至服务端
const handleUploadFile = () => {
  let param = new FormData();
  param.append("file", uploadAppendData.value.file);
  param.append("projectId", uploadAppendData.value.projectId);
  param.append("sheets", uploadAppendData.value.sheets);
  // upload.value.submit();
  uploadAppendData.value.loading = true;
  getFormDataUrl("post", apis.staticDataWarehousing, param)
    .then((res) => {
      ElMessage({
        type: "success",
        message: "上传成功",
      });
      getStaticDataList(uploadAppendData.value.projectId);
    })
    .finally(() => {
      uploadAppendData.value.loading = false;
    });
};

// 下载模板
const downloadTemplate = () => {
  request({
    url: apis.downloadTemplate,
    method: "post",
    responseType: "blob",
  }).then((res) => {
    const timestamp = new Date().getTime();
    blobToFile(res, `模板_${timestamp}.xlsx`);
  });
};

// 静态数据列表
const staticDataList = ref({
  activeIndex: 0, // 当前高亮项
  loading: false,
  data: [],
});
// 获取静态数据列表
const getStaticDataList = (projectId) => {
  uploadAppendData.value.loading = true;
  getFormDataUrl("get", apis.getStaticData, {
    projectId,
  })
    .then((res) => {
      if (res) {
        staticDataList.value.data = [];
        for (let key in res) {
          staticDataList.value.data.push({
            name: key,
            data: res[key],
          });
        }
      }
    })
    .finally(() => {
      uploadAppendData.value.loading = false;
    });
};

// 导出最新模板
const exportLatelyFile = () => {
  console.log("exportLatelyFile");
  request({
    url: apis.exportLatelyFile,
    method: "post",
    responseType: "blob",
  }).then((res) => {
    const timestamp = new Date().getTime();
    blobToFile(res, `最新文件_${timestamp}.xlsx`);
  });
};

// 操作步骤提示框
const operatInstruceDialog = ref({
  visible: false,
});

onMounted(() => {
  // const projectId = route?.query?.projectId
  const projectId = store.getters["project/projectId"];
  if (projectId) {
    uploadAppendData.value.projectId = projectId;
    getStaticDataList(uploadAppendData.value.projectId);
  }
});
</script>
<style lang="scss" scoped>
.right-in {
  -webkit-animation: right-in 0.8s ease-out;
  animation: right-in 0.8s ease-out;
}
.staticFile {
  // min-height: calc(100vh - 180px) !important;
  .box-card {
    .card-header {
      display: flex;
      align-items: center;
      .excelTag,
      .el-button {
        margin: 0 10px;
      }
      .upload-File {
        display: inline-block;
      }
    }
    .card-content {
      height: 100%;
      :deep(.el-tabs) {
        .el-tabs__header {
          height: calc(100vh - 301px);
          .el-tabs__nav-wrap {
            padding: 0 !important;
            // element tabs组件左对齐时上滚和下滚按钮有问题，所以此处隐藏掉，用鼠标滚动事件
            .el-tabs__nav-prev,
            .el-tabs__nav-next {
              display: none;
            }
            .el-tabs__nav-scroll {
              overflow: auto;
              .el-tabs__nav {
                transform: translate() !important;
                .el-tabs__item {
                  text-align: left;
                }
              }
            }
          }
        }
        .el-tabs__content {
          height: calc(100vh - 330px);
          overflow: auto;
          // 动画调整
        }
      }
    }
  }

  :deep(.chooseSheetDialog) {
    .dialog-footer {
      .el-popconfirm {
        padding: 10px !important;
      }
    }
  }
  .operatInstruceDialog {
    h3 {
      color: #a8abb2;
    }
  }
}
</style>
